package com.koudai.reader;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.koudai.reader.android.R;
import com.koudai.reader.conponment.AdWallManager;
import com.koudai.reader.conponment.ListViewAdapter;
import com.koudai.reader.util.Constant;
import com.koudai.reader.util.HttpUtils;
import com.koudai.reader.util.SearchcountUtil;
import com.koudai.reader.vo.Book;
import com.koudai.reader.vo.EndUser;

public class SearchBookActivity extends Activity implements OnScrollListener{
    public static ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(1);
    private ImageView back;
    private EditText keywords;
    private ImageView searchBtn;
    private LinearLayout books_search_no_result;
    private LinearLayout net_error;
    private RelativeLayout load_vew;
    
    private ListView searchResultListView;
    private ListViewAdapter mListViewAdapter;
    
    private Handler internalhandler = new Handler();
    protected ProgressDialog processDialog;
    
    private TextView score;
    private ImageView isVip;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.books_search);
    
        back = (ImageView) findViewById(R.id.search_back_img);
        back.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View paramView) {
                // TODO Auto-generated method stub
                finish();
            }
        });

        
        keywords = (EditText)findViewById(R.id.books_search_edit);
        
        String keyword = getIntent().getStringExtra("keyword");
        if (keyword != null) {
            keywords.setText(keyword);
        }
        
        searchBtn = (ImageView)findViewById(R.id.books_search_btn);
        load_vew = (RelativeLayout) findViewById(R.id.load_view);
        books_search_no_result = (LinearLayout) findViewById(R.id.books_search_no_result);
        net_error = (LinearLayout) findViewById(R.id.net_error);
        
        searchResultListView = (ListView)findViewById(R.id.books_search_keywords);
        
        mListViewAdapter = new ListViewAdapter(this, internalhandler);
        searchResultListView.setAdapter(mListViewAdapter);
        searchResultListView.setOnScrollListener(this);
        
        searchBtn.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View paramView) {

                if (!SearchcountUtil.isReachtoLimit(SearchBookActivity.this) || EndUser.getInstance().isVip()) {
                    // VIP 或者 次数不到三次
                    load_vew.setVisibility(View.VISIBLE);
                    
                    searchResultListView.setVisibility(View.GONE);
                    books_search_no_result.setVisibility(View.GONE);
                    net_error.setVisibility(View.GONE);
                    
                    threadPool.schedule(new AppListHttpRequest(), 0, TimeUnit.MILLISECONDS);

                } else if (EndUser.getInstance().getGold() + Constant.operation.get("search") >= 0) {
                    
                    final Dialog dialog = new AlertDialog.Builder(SearchBookActivity.this).setTitle("温馨提示").setMessage("o.o! 今天搜索超过3次了，需要消耗" + Constant.operation.get("search") +"积分")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                                    new Thread(new Runnable() {

                                        @Override
                                        public void run() {
                                            if (HttpUtils.goldOperation("search")) {
                                                EndUser.getInstance().updateGold(Constant.operation.get("search"));

                                                internalhandler.post(new Runnable() {
                                                    
                                                    @Override
                                                    public void run() {
                                                        load_vew.setVisibility(View.VISIBLE);
                                                        
                                                        searchResultListView.setVisibility(View.GONE);
                                                        books_search_no_result.setVisibility(View.GONE);
                                                        net_error.setVisibility(View.GONE);
                                                        
                                                        score.setText(EndUser.getInstance().getGlodStr());
                                                    }
                                                });

                                                threadPool.schedule(new AppListHttpRequest(), 0, TimeUnit.MILLISECONDS);
                                            } else {
                                                internalhandler.post(new Runnable() {
                                                    public void run() {
                                                        Toast.makeText(SearchBookActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                                                    }
                                                });

                                            }

                                        }
                                    }).start();   
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                                    
                                }
                            }).create();

                    dialog.show();

                } else if (EndUser.getInstance().getGold() + Constant.operation.get("search") < 0) {
                    final Dialog dialog = new AlertDialog.Builder(SearchBookActivity.this).setTitle("温馨提示").setMessage("o.o! 今天搜索超过3次啦，需要消耗" + Constant.operation.get("search") +"积分)，您的积分不足")
                            .setPositiveButton("获取积分", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                                    // TODO 积分墙
                                   AdWallManager.openAppOffers(SearchBookActivity.this); 
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                                    
                                }
                            }).create();

                    dialog.show();

                }

            }
        });
    }
    
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        isVip = (ImageView) findViewById(R.id.vip);
        if (EndUser.getInstance().isVip()) {
            isVip.setVisibility(View.VISIBLE);    
        } else {
            isVip.setVisibility(View.INVISIBLE);    
        }
        
        
        score = (TextView) findViewById(R.id.score);
        score.setText(EndUser.getInstance().getGlodStr());
    }
    
    class AppListHttpRequest implements Runnable {

        @Override
        public void run() {

            try {
                
                if  (keywords.getText().toString().trim().equals("")) {
                    Toast.makeText(SearchBookActivity.this, "请输入书名或者作者", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                final List<Book> bookData = HttpUtils.searchByTerm(keywords.getText().toString());

                internalhandler.post(new Runnable() {

                    @Override
                    public void run() {
                        Iterator<Book> iterator = bookData.iterator();

                        mListViewAdapter.count = 0;
                        if (bookData.size() > 0) {
                            while (iterator.hasNext()) {
                                Book book = iterator.next();
                                mListViewAdapter.bookDataList.put(mListViewAdapter.count++, book);
                            }
                            load_vew.setVisibility(View.GONE);
                            
                            searchResultListView.setVisibility(View.VISIBLE);
                            books_search_no_result.setVisibility(View.GONE);
                            net_error.setVisibility(View.GONE);
                            
                        } else {
                            load_vew.setVisibility(View.GONE);
                            
                            searchResultListView.setVisibility(View.GONE);
                            books_search_no_result.setVisibility(View.VISIBLE);
                            net_error.setVisibility(View.GONE);
                            
                            //没有结果,提示用户
                            notifyNoResult ();
                        }
                        mListViewAdapter.notifyDataSetChanged();
                    }
                });
            } catch (Exception e) {
                load_vew.setVisibility(View.GONE);
                
                searchResultListView.setVisibility(View.GONE);
                books_search_no_result.setVisibility(View.GONE);
                net_error.setVisibility(View.VISIBLE);
                
            }
        }
    }

    private void notifyNoResult () {
        final Dialog dialog = new AlertDialog.Builder(SearchBookActivity.this).setTitle("温馨提示").setMessage("使劲的搜也没搜到您要的结果,您可以继续提交这个请求,我们会尽快为您找到你想看的书")
                .setPositiveButton("继续提交", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        // TODO 积分墙
                        showWait("提交中");
                        
                        new Thread(new Runnable() {
                            
                            @Override
                            public void run() {
                                
                                final boolean result = HttpUtils.addTask(keywords.getText().toString());
                                
                                internalhandler.post(new Runnable() {
                                    public void run() {
                                        
                                        if(result) {
                                            Toast.makeText(SearchBookActivity.this, "提交成功,尽情关注", Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(SearchBookActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });

                                waitClose();
                            }
                        }).start();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        
                    }
                }).create();

        dialog.show();
    }
    
    @Override
    public void onScrollStateChanged(AbsListView paramAbsListView, int paramInt) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onScroll(AbsListView paramAbsListView, int paramInt1, int paramInt2, int paramInt3) {
        // TODO Auto-generated method stub
        
    }


    /**
     * 带等待图标的等待框 参数message：需要显示给用户的字符串
     * */
    public void showWait(final String message) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                processDialog = new ProgressDialog(SearchBookActivity.this);
                processDialog.setMessage(message);
                processDialog.setIndeterminate(true);
                processDialog.setCancelable(false);
                processDialog.show();

            }
        });

    }

    /**
     * 关闭等待框
     * */
    public void waitClose() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (processDialog != null && processDialog.isShowing()) {
                    processDialog.dismiss();
                }
            }
        });
    }
    
}
